package com.icinfo.cloud;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.ItemDataSource;
import com.icinfo.cloud.common.security.config.EnableActuatorWebSecurity;
import com.icinfo.framework.core.druid.filter.Slf4jLogFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName app
 *  TODO
 * @author 彭德志
 * @date 2020/2/25
 * @Version V1.0
 **/
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableScheduling
@MapperScan(basePackages = "com.icinfo.cloud.**.mapper")
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@EnableTransactionManagement
@EnableActuatorWebSecurity
public class UnifiedPunishCaseProviderStarter {
    public static void main(String[] args) {
        System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(UnifiedPunishCaseProviderStarter.class, args);
    }

    @Autowired(required = false)
    private List<DataSource> dataSources;

    @Autowired
    private Slf4jLogFilter slf4jLogFilter;

    @PostConstruct
    public void init() {
        if (dataSources != null && dataSources.size() > 0) {
            dataSources.forEach(dataSource -> {
                if (dataSource instanceof DynamicRoutingDataSource) {
                    final Map<String, DataSource> dataSourcesMap = ((DynamicRoutingDataSource) dataSource).getDataSources();
                    dataSourcesMap.forEach((key, value) -> {
                        if (value instanceof ItemDataSource) {
                            ItemDataSource itemDataSource = (ItemDataSource) value;
                            try {
                                if (itemDataSource.isWrapperFor(DruidDataSource.class)) {
                                    DruidDataSource realDataSource = itemDataSource.unwrap(DruidDataSource.class);
                                    realDataSource.setProxyFilters(Arrays.asList(slf4jLogFilter));
                                }
                            } catch (SQLException ex) {

                            }
                        }
                    });
                }
            });
        }
    }
}
